import { View, Text, ScrollView } from "@tarojs/components";
import { useState, useEffect, useRef, useImperativeHandle, forwardRef } from "react";
import { AtButton, AtModal } from "taro-ui";
import "./index.less";


interface CommandHistoryProps {
  onCommandReceived?: (cmd: any) => void;
}

export interface CommandHistoryRef {
  addCommand: (cmd: any) => void;
}

const CommandHistory = forwardRef<CommandHistoryRef, CommandHistoryProps>((props, ref) => {
  const { onCommandReceived } = props;
  const [commandHistory, setCommandHistory] = useState<string[]>([]);
  const [showFullHistory, setShowFullHistory] = useState(false);
  const scrollViewRef = useRef<any>(null);

  // 暴露给父组件的方法
  useImperativeHandle(ref, () => ({
    addCommand: (cmd: string) => {
      setCommandHistory(prev => {
        // 限制历史记录数量为50条，避免过多占用内存
        const newHistory = [...prev, cmd];
        return newHistory.length > 50 ? newHistory.slice(-50) : newHistory;
      });
      
      // 触发外部回调
      onCommandReceived?.(cmd);
    }
  }));

  // 格式化指令显示
  const formatCommand = (cmd: string) => {
    if (!cmd) return '';
    
    const cmdPlayerIp = cmd.split(':').pop() || '未知玩家';
    const commandType = cmd.split(':').shift() || '';
    
    
    // 根据指令类型格式化显示
    switch (commandType) {
      case 'TAKE_GEMS_SUCCESS':
        return `玩家${cmdPlayerIp}拿取宝石成功`;
      case 'CAN_CLAIM_LEVEL4_CARD':
        return `玩家${cmdPlayerIp}可以获取4级卡片`;
      case 'BUY_CARD_SUCCESS':
        return `玩家${cmdPlayerIp}购买卡片成功`;
      case 'START_GAME':
        return '游戏开始';
      case 'USE_PRIVILEGE_SUCCESS':
        return `玩家${cmdPlayerIp}使用特权成功`;
      case 'RESERVE_CARD_SUCCESS':
        return `玩家${cmdPlayerIp}保留卡片成功`;
      case 'START_NEW_ROUND':
        return '开始新回合';
      case 'PLAY_ANOTHER_ROUND':
        return '进行另一回合';
      case 'CHANGE_CARD_COLOR_SUCCESS':
        return `玩家${cmdPlayerIp}更改卡片颜色成功`;
      case 'TAKE_GEM_FROM_OPPONENT_SUCCESS':
        return `玩家${cmdPlayerIp}从对手拿取宝石成功`;
      case 'GET_PRIVILEGE_SUCCESS':
        return `玩家${cmdPlayerIp}获取特权成功`;
      case 'GEM_BOARD_REFILLED':
        return '宝石盘已补充';
      case 'GAME_END_WIN_BY_COLOR_SCORE':
        return `游戏结束 - 玩家${cmdPlayerIp}按颜色分数获胜`;
      case 'GAME_END_WIN_BY_SCORE':
        return `游戏结束 - 玩家${cmdPlayerIp}按总分获胜`;
      case 'GAME_END_WIN_BY_CROWNS':
        return `游戏结束 - 玩家${cmdPlayerIp}按皇冠数获胜`;
      case 'PLAYER_TURN_STARTED':
        return `玩家${cmdPlayerIp}回合开始`;
      default:
        return `${commandType}: ${cmdPlayerIp}`;
    }
  };

  return (
    <>
      <View className='history-container' onClick={() => setShowFullHistory(true)}>
        <View className='history-header'>
          <Text className='history-title'>行动历史</Text>
          <AtButton 
            size='small' 
            type='secondary' 
            onClick={(e) => {
              e.stopPropagation();
              setCommandHistory([]);
            }}
            className='clear-btn'
          >
            清空
          </AtButton>
        </View>
        <ScrollView 
          className='history-scroll' 
          scrollY 
          ref={scrollViewRef}
        >
          {commandHistory.length > 0 ? (
            commandHistory.map((cmd, index) => (
              <View className='history-item' key={index}>
                <Text className='history-text'>[{new Date().toLocaleTimeString()}] {formatCommand(cmd)}</Text>
              </View>
            ))
          ) : (
            <View className='history-empty'>
              <Text className='history-empty-text'>暂无行动记录</Text>
            </View>
          )}
        </ScrollView>
      </View>

      {/* 完整历史记录弹窗 - 参考宝石盘弹窗样式 */}
      <AtModal 
        isOpened={showFullHistory} 
        onClose={() => setShowFullHistory(false)}
        className='full-history-modal'
      >
        <View className='full-history-header'>
          <Text className='full-history-title'>完整行动历史</Text>
        </View>
        <ScrollView className='full-history-content'>
          {commandHistory.length > 0 ? (
            commandHistory.map((cmd, index) => (
              <View className='full-history-item' key={index}>
                <Text className='full-history-text'>[{new Date().toLocaleTimeString()}] {formatCommand(cmd)}</Text>
              </View>
            ))
          ) : (
            <View className='history-empty'>
              <Text className='history-empty-text'>暂无行动记录</Text>
            </View>
          )}
        </ScrollView>
        <View className='full-history-buttons'>
          <AtButton 
            className='actionBtn closeBtn'
            onClick={() => setShowFullHistory(false)}
          >
            关闭
          </AtButton>
        </View>
      </AtModal>
    </>
  );
});

export default CommandHistory;